package com.easylinkin.linkappapi.quality.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.common.service.CommonService;
import com.easylinkin.linkappapi.common.utils.excel.ExcelConstant;
import com.easylinkin.linkappapi.common.utils.excel.ExcelTools;
import com.easylinkin.linkappapi.common.utils.io.OutputStreamUtil;
import com.easylinkin.linkappapi.quality.entity.ActualMeasureItem;
import com.easylinkin.linkappapi.quality.entity.ActualMeasureType;
import com.easylinkin.linkappapi.quality.entity.vo.ActualMeasureItemVo;
import com.easylinkin.linkappapi.quality.mapper.ActualMeasureItemMapper;
import com.easylinkin.linkappapi.quality.mapper.ActualMeasureTypeMapper;
import com.easylinkin.linkappapi.quality.service.ActualMeasureItemService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * ActualMeasureItem表服务实现类
 *
 * @author zhengwen
 * @date 2022/08/30
 */
@Slf4j
@Service("actualMeasureItemService")
public class ActualMeasureItemServiceImpl extends ServiceImpl
        <ActualMeasureItemMapper, ActualMeasureItem> implements ActualMeasureItemService {
    @Resource
    private CommonService commonService;
    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;

    @Resource
    private ActualMeasureTypeMapper actualMeasureTypeMapper;

    @Override
    public boolean saveOne(ActualMeasureItem appQualityActualMeasureItem) {
        commonService.setCreateAndModifyInfo(appQualityActualMeasureItem);
        // appQualityActualMeasureItem.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validParamRequired(appQualityActualMeasureItem);
        validRepeat(appQualityActualMeasureItem);
        validParamFormat(appQualityActualMeasureItem);
        return save(appQualityActualMeasureItem);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOne(ActualMeasureItem appQualityActualMeasureItem) {
        Assert.notNull(appQualityActualMeasureItem.getId(), "id不能为空");
        commonService.setModifyInfo(appQualityActualMeasureItem);
        //appQualityActualMeasureItem.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        validRepeat(appQualityActualMeasureItem);
        validParamFormat(appQualityActualMeasureItem);
        return updateById(appQualityActualMeasureItem);
    }

    @Override
    public IPage<ActualMeasureItem> selectPage(Page page, ActualMeasureItem appQualityActualMeasureItem) {
        //appQualityActualMeasureItem.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        return baseMapper.selectPage(page, appQualityActualMeasureItem);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByIds(List<Long> idList) {
        return removeByIds(idList);
    }

    @Override
    public void export(ActualMeasureItem appQualityActualMeasureItem, HttpServletRequest request, HttpServletResponse
            response) {

        IPage<ActualMeasureItem> page = selectPage(new Page(0, -1), appQualityActualMeasureItem);
        List<ActualMeasureItem> records = page.getRecords();
        List
                <ActualMeasureItemVo> appQualityActualMeasureItemVos = new ArrayList<>();
        for (ActualMeasureItem expert : records) {
            appQualityActualMeasureItemVos.add(new ActualMeasureItemVo(expert));
        }

        String keyValue = "名称:name,租户id:tenantId";
        String title = "ActualMeasureItem导出数据";
        String fileName = title + ".xls";
        try {
            OutputStream outputStream = OutputStreamUtil
                    .getOutputStream(request, response, fileName);
            ExcelTools.exportExcel(outputStream, keyValue, appQualityActualMeasureItemVos, ExcelConstant.XLS, title);
            response.flushBuffer();
            outputStream.close();
        } catch (IOException e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！IOException异常" + e.getMessage());
        } catch (Exception e) {
            log.error("excel导出失败", e);
            throw new RuntimeException("excel导出失败！" + e.getMessage());
        }
    }

    @Override
    public RestMessage addActualItem(ActualMeasureItemVo actualMeasureItemVo) {
        Long typeId = actualMeasureItemVo.getMeasureTypeId();
        cn.hutool.core.lang.Assert.isTrue(typeId != null,"分类ID为空");

        //查询分类
        ActualMeasureType actualMeasureType = actualMeasureTypeMapper.selectById(typeId);
        cn.hutool.core.lang.Assert.isTrue( actualMeasureType != null,"分类不存在");

        Integer itemType = actualMeasureType.getItemType();
        cn.hutool.core.lang.Assert.isTrue(itemType.equals(3),"算法只能在测量项目下新增");

        ActualMeasureItem actualMeasureItem = new ActualMeasureItem();
        BeanUtil.copyProperties(actualMeasureItemVo,actualMeasureItem, CopyOptions.create().setIgnoreNullValue(true));

        //参数补充
        actualMeasureItem.setCreator("0");
        actualMeasureItem.setCreateTime(DateUtil.date());
        actualMeasureItem.setModifier(actualMeasureItem.getCreator());
        actualMeasureItem.setModifyTime(actualMeasureItem.getCreateTime());
        actualMeasureItem.setDeleteState(1);

        int inNum = baseMapper.insert(actualMeasureItem);
        if(inNum != 1){
            return RestBuilders.errorBuilder().message("保存失败").build();
        }

        return RestBuilders.successBuilder().data(actualMeasureItem).build();
    }

    @Override
    public ActualMeasureItem getOneById(Serializable id) {
        return baseMapper.getOneById(id);
    }

    /**
     * 校验重复
     */
    private void validRepeat(ActualMeasureItem appQualityActualMeasureItem) {
        /* QueryWrapper<ActualMeasureItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", appQualityActualMeasureItem.getName());
        queryWrapper.eq("tenant_id", linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<ActualMeasureItem> list = baseMapper.selectList(queryWrapper);
        if (list.size() == 0) {
            return;
        }
        if (list.size() > 1) {
            throw new BusinessException("名称有重复");
        }
        if (ObjectUtils.isEmpty(appQualityActualMeasureItem.getId())) {
            throw new BusinessException("名称已存在");
        }
        if (!appQualityActualMeasureItem.getId().equals(list.get(0).getId())) {
            throw new BusinessException("名称已存在");
        }
                    */

    }


    /**
     * 校验参数必填
     */
    private void validParamRequired(ActualMeasureItem appQualityActualMeasureItem) {
        //Assert.notNull(appQualityActualMeasureItem, "参数为空");
        //Assert.isTrue(StringUtils.isNotBlank(appQualityActualMeasureItem.getName()), "名称为空");
    }

    /**
     * 校验参数格式
     */
    private void validParamFormat(ActualMeasureItem appQualityActualMeasureItem) {
        //Assert.isTrue(appQualityActualMeasureItem.getName() == null || appQualityActualMeasureItem.getName().length() <= 50,
        //        "名称超长");
    }
}

